//
//  BHHomeViewController.m
//  xinlangweibo0621
//
//  Created by boldseas on 2017/6/21.
//  Copyright © 2017年 renbohan. All rights reserved.
//

#import "BHHomeViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "BHHomeTitleBtn.h"
#import "BHHomeTitleBtn.h"
#import "BHAccountTool.h"
#import "BHAccount.h"
#import <AFNetworking.h>
#import "BHJsonSwitch.h"
#import <UIImageView+WebCache.h>
#import "BHUser.h"
#import "BHStatus.h"
#import <MJExtension.h>
#import <Masonry.h>
#import "BHLoadMoreFooter.h"
#import "BHStatusCell.h"


@interface BHHomeViewController ()

@property (nonatomic, strong) NSMutableArray *statusesArray;

@end

@implementation BHHomeViewController

-(NSMutableArray *)statusesArray{
    if (!_statusesArray) {
        self.statusesArray = [NSMutableArray array];
    }
    return _statusesArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.tableView.estimatedRowHeight = 200;
//    self.tableView.rowHeight = 88;
    
//    [self.tableView registerClass:[BHStatusCell class] forCellReuseIdentifier:@"status"];
    
    //设置导航栏左右的按钮
    [self setupNav];
    
    //获得用户昵称信息
    [self setupUserInfo];
    
//    //加载新的微博数据
//    [self loadNewStatus];
    
    //下拉刷新
    [self setupDownRefresh];
    
    //上拉刷新
    [self setupUpRefresh];
    
//    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(setupUnreadCount) userInfo:nil repeats:YES];

}

/** 获得最新的微博未读数 */
- (void)setupUnreadCount{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    BHAccount *account = [BHAccountTool account];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = account.access_token;
    parameters[@"uid"] = account.uid;
    
    [manager GET:@"https://rm.api.weibo.com/2/remind/unread_count.json" parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *status = [responseObject[@"status"] description];
        if ([status isEqualToString:@"0"]) {
            self.tabBarItem.badgeValue = nil;
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        }else{
            self.tabBarItem.badgeValue = status;
            [UIApplication sharedApplication].applicationIconBadgeNumber = status.intValue;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败:%@", error);
    }];
}

/** 上拉刷新 */
- (void)setupUpRefresh{
    BHLoadMoreFooter *footer = [BHLoadMoreFooter loadMoreFooter];
    footer.hidden = YES;
    self.tableView.tableFooterView = footer;
}

/** 下拉刷新 */
- (void)setupDownRefresh{
    UIRefreshControl *control = [[UIRefreshControl alloc]init];
    [control addTarget:self action:@selector(refreshStatesControl:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:control];
}

/** 下拉加载新数据 */
- (void)refreshStatesControl:(UIRefreshControl *)control{
    //    https://api.weibo.com/2/statuses/home_timeline.json
    //    access_token  string 	采用OAuth授权方式为必填参数，OAuth授权后获得。
    //    since_id 	int64 	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
    //    max_id 	int64 	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
    //    count 	int 	单页返回的记录条数，最大不超过100，默认为20。
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    BHAccount *account = [BHAccountTool account];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = account.access_token;
    BHStatus *firstStasus = [self.statusesArray firstObject];
    if (firstStasus) {
        parameters[@"since_id"] = firstStasus.idstr;
    }
    
    [manager GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *newArray = [BHStatus mj_objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        
        NSRange range = NSMakeRange(0, newArray.count);
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statusesArray insertObjects:newArray atIndexes:set];
        
        [self.tableView reloadData];
        
        [control endRefreshing];
        
        [self showNewStatusCount:newArray.count];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败:%@", error);
    }];
}

/** 上拉加载老微博 */
- (void)loadMoreStatus{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    BHAccount *account = [BHAccountTool account];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = account.access_token;
    BHStatus *lastStatus = self.statusesArray.lastObject;
    if (lastStatus) {
        long long maxID = lastStatus.idstr.longLongValue - 1;
        parameters[@"max_id"] = @(maxID);
    }
    
    
    [manager GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *newStatus = [BHStatus mj_objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        [self.statusesArray addObjectsFromArray:newStatus];
        [self.tableView reloadData];
        self.tableView.tableFooterView.hidden = YES;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败:%@",error);
        self.tableView.tableFooterView.hidden = YES;
    }];
}

/** 显示最新微博的数量 */
- (void)showNewStatusCount:(NSUInteger)count{
    UILabel *label = [[UILabel alloc]init];
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    
    if (count == 0) {
        label.text = @"没有新的微博,请稍后再试";
    }else{
        label.text = [NSString stringWithFormat:@"共有%lu条新微博", count];
    }
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:15];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.height.mas_equalTo(self.view).multipliedBy(0.05);
        make.bottom.mas_equalTo(self.navigationController.navigationBar);
    }];
    [self.navigationController.view layoutIfNeeded];
    
    CGFloat duration = 1.0;
    [UIView animateWithDuration:duration animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, label.frame.size.height);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:duration delay:1.0 options:UIViewAnimationOptionCurveLinear animations:^{
            label.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}



/** 加载最新的微博数据  test*/
- (void)loadNewStatus{
//    https://api.weibo.com/2/statuses/home_timeline.json
//    access_token  string 	采用OAuth授权方式为必填参数，OAuth授权后获得。
//    since_id 	int64 	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
//    max_id 	int64 	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
//    count 	int 	单页返回的记录条数，最大不超过100，默认为20。
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    BHAccount *account = [BHAccountTool account];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = account.access_token;
    
    [manager GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.statusesArray = [BHStatus mj_objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

/** 设置用户昵称 */
- (void)setupUserInfo{
//    https://api.weibo.com/2/users/show.json
//    http://api.jirengu.com/weather.php?callback=getWeather
//    access_token	string 	采用OAuth授权方式为必填参数，OAuth授权后获得。
//    uid 	int64 	需要查询的用户ID。
//    screen_name 	string 	需要查询的用户昵称。
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    BHAccount *account = [BHAccountTool account];
//    /Users/renbohan/Desktop
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = account.access_token;
    parameters[@"uid"] = account.uid;
    
    [manager GET:@"https://api.weibo.com/2/users/show.json" parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        BHUser *user = [BHUser mj_objectWithKeyValues:responseObject];
        UIButton *titleBtn = (UIButton *) self.navigationItem.titleView;
        [titleBtn setTitle:user.name forState:UIControlStateNormal];
        account.name = user.name;
        [BHAccountTool saveAccount:account];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

/** 设置导航栏左右的按钮 */
- (void)setupNav{
    //设置导航栏左右的按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_friendsearch" highImage:@"navigationbar_friendsearch_highlighted" target:self action:@selector(frendSearch)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImage:@"navigationbar_pop" highImage:@"navigationbar_pop_highlighted" target:self action:@selector(pop)];
    
    NSString *name = [BHAccountTool account].name;
    BHHomeTitleBtn *titleBtn = [[BHHomeTitleBtn alloc]init];
    CGRect titleBtnF = titleBtn.frame;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    titleBtnF.size = CGSizeMake(screenSize.width - 100, 35);
    titleBtn.frame = titleBtnF;
    [titleBtn setTitle:name?name:@"首页" forState:UIControlStateNormal];
    [titleBtn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleBtn;
}

- (void)titleClick:(BHHomeTitleBtn *)titleBtn{
    titleBtn.selected = NO;
}



- (void)frendSearch{
    NSLog(@"frendSearch");
}

- (void)pop{
    NSLog(@"pop");
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.statusesArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BHStatusCell *cell = [BHStatusCell cellWithTableView:tableView];
    
    cell.status = self.statusesArray[indexPath.row];
    
    return cell;
//
//    static NSString *ID = @"status";
//    BHStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//    BHStatus *status = self.statusesArray[indexPath.row];
//    cell.status = status;
//    if (cell==nil) {
//        cell = [[BHStatusCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
//    }
//    return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.statusesArray.count == 0 || self.tableView.tableFooterView.isHidden == NO) return;
    
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat judgeOffsetY = scrollView.contentSize.height + scrollView.contentInset.bottom - scrollView.frame.size.height - self.tableView.tableFooterView.frame.size.height;
    
    if (offsetY >= judgeOffsetY) {
        self.tableView.tableFooterView.hidden = NO;
        [self loadMoreStatus];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    BHStatus *status = self.statusesArray[indexPath.row];
    
    CGFloat cellHeight = status.cellHeight;
    
    return cellHeight;
}




@end
